﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Bus.Controllers;
using Way.Bus.WMS.Model;
using Way.Contract.Data;
using Way.EAP.DataAccess.Data;
using Way.EAP.DataAccess.Entity;
using Way.Contract.MVC;
using Way.Contract.Data.ControllerData;
using Way.Contract;
using Way.Bus.Model;
using System.Data;
using Way.EAP.DataAccess.Regulation;
using Way.Bus.Wms.Controllers.BaseData;


namespace Way.Bus.WMS.Controllers
{
    public class MoveOrderController : BusinessController
    {
        /// <summary>
        /// 描述：移位单控制器
        /// 作者：路聪
        /// 创建日期:2013-02-27
        /// </summary>
        public MoveOrderController() : base(new MoveOrder()) { }
        public MoveOrderController(IModel model) : base(model) { }

        //是否启用审核
        public override bool IsReviewedState
        {
            get
            {
                return false
;
            }
        }
        //是否启用提交
        public override bool IsSubmit
        {
            get
            {
                return false;
            }
        }
        //是否启用回收站
        public override bool IsClearAway
        {
            get
            {
                return false;
            }
        }

        public override bool IsPrint
        {
            get
            {
                return false;
            }
        }

        #region 初始化数据方法

        /// <summary>
        /// 外键查询初始化界面显示
        /// </summary>
        /// <param name="model"></param>
        /// <param name="data"></param>
        protected override void OnForeignIniting(IModel model, InitData data)
        {
            if (this.fdata.filedname == "DEPOTWBS")
            {
                //初始化仓库和货位
                foreach (ItemData d in data.modeldata.childitem)
                {
                    MoveOrderController.InitWareHouse(data.modeldata, d, this.fdata.filedname);
                }
            }
            if (this.fdata.filedname == "MATERIALCODE")
            {
                StockInfoMaterialsController.OnInitForeignStockInfoMaterials((MoveOrderMaterials)model, data);
                foreach (ItemData d in data.modeldata.childitem)
                {
                    if (d.IsField("DID"))
                    {
                        d.foreign.isfkey = true;
                        d.foreign.displayname = "DCODE";
                    }
                }
            }
        }

        protected override void OnGetWhereing(IModel m, List<SQLWhere> where, loadItem item)
        {
            base.OnGetWhereing(m, where, item);
            if (isqx)
                WmsRoleDataController.SearchManage(this, where, item);
        }
        protected override void OnForeignLoading(IModel model, loadItem item)
        {
            base.OnForeignLoading(model, item);
            if (this.fdata.filedname == "DEPOTWBS")
            { isqx = true; }
            else
            { isqx = false; }
        }
        bool isqx = false;
        protected override ReadTable OnForeignLoad(IModel model, loadItem item)
        {
            
            //设置仓库选择框只能选择仓库信息
            if (this.fdata.filedname == "DEPOTWBS")
            {
                item.rowsql = "select * from (" + item.rowsql + ") t " + "where WHTYPE=0";
                isqx = false;
            }

            if (this.fdata.filedname == "MATERIALCODE" || this.fdata.filedname == "FROMDEPOT")
            {
                if (ActionItem == null)
                    ActionItem = EntityHelper.ToEntity(this.fdata.eventrow, typeof(MoveOrder));
                int ckid = 0;
                if ((int)this.ActionItem["DEPOTWBS"] != 0)
                    ckid = int.Parse(this.ActionItem["DEPOTWBS"].ToString());
                else
                    throw new Exception("异常：请先选择移位仓库！");
               
                StockInfoView view = new StockInfoView();
                item.rowsql= view.getGetSearchSQL();
                string strSQL = " and wid=" + ckid;
                if (ActionItem["STAY5"] != null && ActionItem["STAY5"].ToString() != "")
                {
                    strSQL += " and (MCODE='" + ActionItem["STAY5"].ToString() + "' or CUSTOMEAN13='" + ActionItem["STAY5"].ToString() + "')";
                }
                if (ActionItem["STAY4"] != null && ActionItem["STAY4"].ToString() != "")
                {
                    strSQL += " and DCODE='" + ActionItem["STAY4"].ToString() + "'";
                }
                foreach (SQLWhere sw in item.whereList)
                {
                    if (sw.ColumnName.EndsWith("IsDisable"))
                        continue;
                    //sw.ColumnName = sw.ColumnName.Replace(".StockInfoView", "");
                    sw.ColumnName = sw.ColumnName.Replace("StockInfoView.", "");//modify by fisher 2016.03.15 22:03
                    strSQL += " and " + sw.where();
                }
                item.sort = "MID";
                item.rowsql = "select * from (select a.*,b.BATCH,b.ISPERIOD,b.SEQUENCECODE,b.CUSTOMEAN13,b.BARCODEFM from (" + item.rowsql + ") a,Acc_Bus_BusinessCommodity b where a.mid=b.id ) Acc_Bus_BusinessCommodity where 1=1 " + strSQL;
            }
            if (this.fdata.filedname == "TODEPOT")
            {
                int ckid = 0;
                if ((int)this.ActionItem["DEPOTWBS"] != 0)
                    ckid = int.Parse(this.ActionItem["DEPOTWBS"].ToString());
                else
                    throw new Exception("异常：请先选择仓库！");
                string spid = "";
                MoveOrderMaterials mm = EntityHelper.ToEntity(this.fdata.eventrow, typeof(MoveOrderMaterials)) as MoveOrderMaterials;
                if (mm != null && mm["MATERIALCODE"] != null && !string.IsNullOrEmpty(mm["MATERIALCODE"].ToString()))
                    spid = mm["MCODE"].ToString();
                else
                    throw new Exception("异常：请先选择商品！");

                IDataAction action = this.model.GetDataAction();
                //string sql = "";
                
                //if (this.fdata.filedname == "FROMDEPOT")
                //{
                //    item.rowsql = "select t2.ID, t2.CODE, t2.WAREHOUSENAME, t3.ID as HQID, t3.WAREHOUSENAME as HQName,t4.ID as CKID, t4.WAREHOUSENAME as CKName from Acc_WMS_WareHouse t2 left join Acc_WMS_WareHouse t3 on t3.ID = t2.PARENTID left join Acc_WMS_WareHouse t4 on t4.ID = t3.PARENTID where t4.ID='" + ckid + "' and exists (select * from Acc_WMS_InfoMaterials t1,Acc_Bus_BusinessCommodity t5 where t1.MCODE = t5.Code and t1.depotwbs = t2.ID and t5.ID='" + spid + "')";
                //}
                //else
                //{
                //    item.rowsql = "select t2.ID, t2.CODE, t2.WAREHOUSENAME, t3.ID as HQID, t3.WAREHOUSENAME as HQName,t4.ID as CKID, t4.WAREHOUSENAME as CKName from Acc_WMS_WareHouse t2 left join Acc_WMS_WareHouse t3 on t3.ID = t2.PARENTID left join Acc_WMS_WareHouse t4 on t4.ID = t3.PARENTID where t4.ID='" + ckid + "'";
                //}
            }
            return base.OnForeignLoad(model, item);
        }

        protected override void OnForeignLoaded(IModel model, ReadTable table)
        {
            //选择货位:源货位从库存中取，目标货位从仓库表取
            //if (this.fdata.filedname == "TODEPOT")
            //{
            //    foreach (DataRow r in table.rows.Rows)
            //    {
            //        //r["CODE"] = r["HQName"];
            //        //r["DEPOTWBS"] = r["WAREHOUSENAME"];
            //        r["CODE"] = r["CODE"];
            //        //r["WAREHOUSENAME"] = r["HQName"];
            //    }

            //}
            if (this.fdata.filedname == "FROMDEPOT" || this.fdata.filedname == "MATERIALCODE")
            {
                table.rows.Columns.Add("KCID");
                table.rows.Columns.Add("CODE");
                table.rows.Columns.Add("FNAME");
                table.rows.Columns.Add("FMODEL");
                foreach (DataRow r in table.rows.Rows)
                {
                    r["KCID"] = r["ID"];
                    r["FNAME"] = r["MNAME"];
                    r["FMODEL"] = r["MODEL"];
                    r["ID"] = r["MID"];
                    if (this.fdata.filedname == "MATERIALCODE")
                    {
                        r["CODE"] = r["MCODE"];
                    }
                    if (this.fdata.filedname == "FROMDEPOT")
                    {
                        r["CODE"] = r["DCODE"];
                    }
                   
                }
            }
            base.OnForeignLoaded(model, table);
        }

        public static void InitWareHouse(ModelData data, ItemData item, string fieldname)
        {
            if (data.name.EndsWith("WareHouse"))
            {
                item.visible = false;
                if (fieldname.Equals("DEPOTWBS"))
                {
                    data.title = "仓库信息";
                    if (item.IsField("CODE"))
                    {
                        item.title = "仓库编码";
                        item.index = 0;
                        item.visible = true;
                    }
                    if (item.IsField("WAREHOUSENAME"))
                    {
                        item.title = "仓库名称";
                        item.index = 1;
                        item.visible = true;
                    }
                }
                else if (fieldname.Equals("FROMDEPOT") || fieldname.Equals("TODEPOT"))
                {
                    data.title = "货位信息";
                    if (item.IsField("CODE"))
                    {
                        item.title = "货位";
                        item.index = 0;
                        item.visible = true;
                    }
                    if (item.IsField("WAREHOUSENAME"))
                    {
                        item.title = "货区";
                        item.index = 1;
                        item.visible = true;
                    }
                }
            }
            
        }

        protected override void OnInitViewChildItem(Way.Contract.Data.ModelData data, Way.Contract.Data.ItemData item)
        {
            if (data.name.EndsWith("MoveOrder"))
            {
                switch (item.field.ToLower())
                {
                    case "modifiedby":
                    case "modifieddate":
                    case "isdisable":
                    case "isdelete":
                    case "id":
                        item.visible = false;
                        item.isedit = false;
                        break;
                    case "depotwbs":
                        item.required = true;
                        break;
                    case "code":
                        item.title = "移位单号";
                        item.visible = true;
                        item.disabled = true;
                        break;
                    case "rowindex":
                        item.visible = true;
                        item.disabled = true;
                        break;
                    case "submiteddate":
                    case "submitedby":
                    case "createdby":
                    case "creationdate":
                    case "reviewedby":
                    case "revieweddate":
                    case "issubmited":
                    case "isreviewed":
                    case "stay1":
                    case "stay2":
                    case "stay3":
                    case "stay4":
                    case "stay5":
                    case "pid":
                        item.disabled = true;
                        item.visible = false;
                        break;
                }
            }
            if (data.name.EndsWith("StockSequence"))
            {
                data.visible = false;
            }
            if(data.name.EndsWith("MoveSequence"))
            {
                item.visible = false;
                if (item.IsField("SEQUENCECODE"))
                {
                    item.visible = true;
                    item.title = "序列号";
                }
            }
            if (data.name.EndsWith("MoveOrderMaterials"))
            {
                //data.disabled = true;
                if (item.field == "DEPOTWBS")
                {
                    item.index = 3;

                }
                if (item.IsField("MATERIALCODE"))
                {
                    item.title = "货物名称";
                    if (item.foreign != null)
                    {
                        //item.foreign.rowdisplay.Add("FMOBILE", "FMOBILE");//key是联系人表字段，value是客户表字段
                        item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                        item.foreign.rowdisplay.Add("CODE", "MCODE");
                        item.foreign.rowdisplay.Add("BATCHNO", "BATCHNO");
                        item.foreign.rowdisplay.Add("NUM", "NUM");
                        item.foreign.rowdisplay.Add("DID", "FROMDEPOT");
                        item.foreign.rowdisplay.Add("SUBNO", "SENBATCHNO");
                    }
                }
              
                if (item.IsField("SENBATCHNO"))
                    item.title = "有效期";
                switch (item.field.ToLower())
                {
                    case "createdby":
                    case "creationdate":
                    case "submiteddate":
                    case "submitedby":
                    case "modifiedby":
                    case "modifieddate":
                    case "reviewedby":
                    case "revieweddate":
                    case "issubmited":
                    case "isreviewed":
                    case "isdisable":
                    case "isdelete":
                    case "id":
                    case "code":
                    case "stay1":
                    case "stay2":
                    case "stay3":
                    case "stay4":
                    case "stay5":
                    case "sourcecode":
                    case "parentid":
                    case "pid":
                        item.visible = false;
                        item.isedit = false;
                        break;
                    case "materialcode":
                        item.required = true;
                        item.index = 1;
                        break;
                    case "mcode":
                        item.title = "货物编码";
                        item.disabled = true;
                        item.index = 2;
                        break;
                    case "fmodel":
                        item.disabled = true;
                        item.index = 3;
                        break;
                    case "batchno":
                        item.index = 4;
                        break;
                    case "num":
                        item.required = true;
                        item.index = 5;
                        break;
                    case "fromdepot":
                        item.index = 6;
                        item.required = true;
                        break;
                    case "fromport":
                        item.visible = false;
                        item.index = 7;
                        break;
                    case "todepot":
                        item.index = 8;
                        item.required = true;
                        break;
                    case "toport":
                        item.visible = false;
                        item.index = 9;
                        break;
                }
            }
        }


        #endregion

        [ActionCommand(name = "导入", title = "导入", index = 6, icon = "icon-down", isselectrow = false, editshow = true, onclick = "import4")]
        public void ImportExcel()
        {

        }

        //显示在菜单
        protected override string OnControllerName()
        {
            return "移位单管理";
        }
        //菜单中url路径
        protected override string OnGetPath()
        {
            return "Views/WMS/Materials/MoveOrder.htm";
        }
        //开发人
        protected override string OnGetAuthor()
        {
            return "";
        }
        //说明
        protected override string OnGetControllerDescription()
        {
            return "移位单管理";
        }

        protected override void OnAdding(Way.Contract.MVC.ControllerBase.SaveEvent item)
        {
            //MoveDepots(item);
            startMove((MoveOrder)item.Item);
            base.OnAdding(item);
        }

        protected override void OnEditing(Way.Contract.MVC.ControllerBase.SaveEvent item)
        {
            //MoveDepots(item);
            startMove((MoveOrder)item.Item);
            base.OnEditing(item);
        }
        protected void startMove(MoveOrder order)
        {
            foreach (MoveOrderMaterials o in order.Materials)
                updateMove(order, o);
        }
        protected void updateMove(MoveOrder order, MoveOrderMaterials item)
        {
            if (order.DEPOTWBS <= 0)
                throw new Exception("异常：移位仓库未选择！");
            if (item.NUM <= 0)
                throw new Exception("异常：移位数量必须大于零！");
            StockInfoView view = new StockInfoView();
            string sql = "";
            if (item.SourceID > 0)
                sql = view.getGetSearchSQL() + " where id=" + item.SourceID;
            else
                sql = StockInfoView.GetStockSQL(0, order.DEPOTWBS, int.Parse(item.MATERIALCODE), item.FROMDEPOT, item.BATCHNO,item.SENBATCHNO);
            DataTable table = this.model.GetDataAction().GetDataTable(sql);
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataColumn c in table.Columns)
                {
                    if (((IEntityBase)view).IsHaveProperty(c.ColumnName))
                        view[c.ColumnName] = table.Rows[0][c];
                }
                if (item.NUM > view.KYNUM)
                    throw new Exception("异常：移位数量" + item.NUM + "大于库存可用数量" + view.KYNUM + ",不能移位！");
                string tname = "Acc_WMS_InfoMaterials";
                int did = 0;
                if(!int.TryParse(item.TODEPOT,out did))
                    did= WareHouse.GetDepotwesID(order.DEPOTWBS, item.TODEPOT, this.model.GetDataAction());
                if (did <= 0)
                    throw new Exception("异常：目标位置" + item.TODEPOT + "未找到，请修改目标位置！");
                string tkcsql = StockInfoView.GetStockSQL(0, order.DEPOTWBS, int.Parse(item.MATERIALCODE), did, item.BATCHNO, item.SENBATCHNO);
                DataTable tktable = this.model.GetDataAction().GetDataTable(tkcsql);
                int tkid = 0;
                double kcnum = 0;
                if (tktable != null && tktable.Rows.Count > 0)
                {
                    tkid = int.Parse(tktable.Rows[0]["ID"].ToString());
                    kcnum = double.Parse(tktable.Rows[0]["num"].ToString()) + item.NUM;
                }

                item.TODEPOT = did.ToString();
                if (view.KYNUM == view.NUM && item.NUM == view.KYNUM)
                {
                    string update = "update " + tname + " set DEPOTWBS='" + did + "' where id=" + view.ID;

                    if (tkid == 0)
                        this.model.GetDataAction().Execute(update);
                    else
                    {
                        IDataAction action = this.model.GetDataAction();
                        try
                        {
                            action.StartTransation();
                            string update1 = "update " + tname + " set num='" + kcnum + "' where id=" + tkid;
                            string delete = "delete from " + tname + " where id=" + view.ID;
                            string updatec = "update " + ((IHierarchicalEntityView)view.StockSequence).ChildEntity.ToString() + " set STOCKINFOMATERIALSID=" + tkid + " where STOCKINFOMATERIALSID=" + view.ID;
                            action.Execute(update1);
                            action.Execute(delete);
                            action.Execute(updatec);
                            action.Commit();
                        }
                        finally
                        {
                            action.EndTransation();
                        }
                    }
                }
                else
                {
                    IDataAction action = this.model.GetDataAction();
                    try
                    {
                        Materials m = item.GetForeignObject<Materials>(action);
                        if (m.SEQUENCECODE && item.MoveSequence.Count == 0)
                        {
                            throw new Exception("异常：商品为序列号管理，必须录入序列号！");
                        }
                        else
                        {
                            string ssss = "select a.SEQUENCECODE,b.ID,b.DEPOTWBS,b.WAREHOUSEID from Acc_WMS_InfoInSequence a,Acc_WMS_InfoMaterials b"
                               +" where a.STOCKINFOMATERIALSID=b.ID and a.SEQUENCECODE='{0}'";
                            foreach (MoveSequence ms in item.MoveSequence)
                            {
                                DataTable t = action.GetDataTable(string.Format(ssss, ms.SEQUENCECODE));
                                if (t != null && t.Rows.Count > 0)
                                {
                                    if (item.FROMDEPOT.ToString() != t.Rows[0]["DEPOTWBS"].ToString())
                                        throw new Exception("异常：序列号" + ms.SEQUENCECODE + ",不在货位" + item.GetAppendPropertyValue("FROMDEPOT") + "，不能移动，请检查！");
                                }
                                else
                                {
                                    throw new Exception("异常：序列号" + ms.SEQUENCECODE + ",在库存中不存在不能移动，请检查！");
                                }
                            }
                        }
                        double num = view.NUM - item.NUM;
                        action.StartTransation();
                        string update = "update " + tname + " set num='" + num + "' where id=" + view.ID;
                        string insert = "";
                        if (tkid == 0)
                            insert = "insert into " + tname + "(Code,MCODE,FMODEL,BATCHNO,SENBATCHNO,WAREHOUSEID,DEPOTWBS,NUM) values(" + view.MID + ",'" + view.MCODE + "','" + view.model + "','" + view.BATCHNO + "','" + view.SUBNO + "'," + view.WID + "," + did + "," + item.NUM + ")";
                        else
                            insert = "update " + tname + " set num='" + kcnum + "' where id=" + tkid;
                        action.Execute(update);
                        object id = tkid;
                        if (tkid == 0)
                            action.Execute(insert, out id);
                        else
                            action.Execute(insert);
                        if (item.MoveSequence.Count > 0)
                        {
                            string seq = "";
                            string seqtablename = ((IHierarchicalEntityView)view.StockSequence).ChildEntity.ToString();
                            string cinsert = "insert into {0} (STOCKINFOMATERIALSID,SEQUENCECODE,IsDelete,IsDisable) values({1},'{2}',0,0)";
                            foreach (MoveSequence ms in item.MoveSequence)
                            {
                                if (string.IsNullOrEmpty(seq))
                                    seq = "'" + ms.SEQUENCECODE + "'";
                                else
                                    seq += ",'" + ms.SEQUENCECODE + "'";
                                action.Execute(string.Format(cinsert, seqtablename, id, ms.SEQUENCECODE));
                            }
                            string delete = "delete from " + seqtablename + " where STOCKINFOMATERIALSID=" + view.ID + " and SEQUENCECODE in (" + seq + ")";
                            action.Execute(delete);
                        }
                        action.Commit();
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        action.EndTransation();
                    }
                }
            }
        }


        [WhereParameter]
        public List<InfoInSequence> InfoSequences { get; set; }

        public virtual void MoveDepots(Way.Contract.MVC.ControllerBase.SaveEvent item)
        {
            IDataAction action = this.model.GetDataAction();
            try
            {
                action.StartTransation();//开启事物
                
                MoveOrder mo = item.Item as MoveOrder;
                StockInfoMaterials sm;
                StockInfoMaterialsController sims = new StockInfoMaterialsController();
                Materials m;
                foreach (MoveOrderMaterials mom in mo.Materials)
                {
                    sm = new StockInfoMaterials();
                    m = mom.GetForeignObject<Materials>(this.model.GetDataAction());
                    sm.DEPOTWBS = mom.FROMDEPOT.ToString();
                    sm.PORTCODE = mom.FROMPORT;
                    sm.NUM = mom.NUM;
                    sm.Code = mom.MATERIALCODE;
                    sm.BATCHNO = mom.BATCHNO;
                    sm.WAREHOUSEID = mo.DEPOTWBS;
                    sm.MCODE = m.Code;
                    sm.FMODEL = m.FMODEL;
                    if (InfoSequences != null)
                    {
                        for (int i = 0; i < InfoSequences.Count; i++)
                        {
                            sm.StockSequence.Add(InfoSequences[i]);
                        }
                    }
                    sims.putin(sm, "出库", action);
                    int result;
                    if (int.TryParse(mom.TODEPOT, out result))
                    {
                        sm.DEPOTWBS = result.ToString();
                    }
                    else
                    {
                       sm.DEPOTWBS= WareHouse.GetDepotwesID(sm.WAREHOUSEID, mom.TODEPOT, action).ToString();
                       mom.TODEPOT = sm.DEPOTWBS;
                    }
                    if (!string.IsNullOrEmpty(mom.TOPORT))
                        sm.PORTCODE = mom.TOPORT;
                    sims.putin(sm, "入库", action);
                }
                action.Commit();
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                action.EndTransation();//结束事物
            }
        }

        /// <summary>
        /// 设置按钮显示名称
        /// </summary>
        /// <param name="commands"></param>
        /// <returns></returns>
        protected override ActionCommand[] OnInitCommand(ActionCommand[] commands)
        {
            ActionCommand[] coms = base.OnInitCommand(commands);
            //获取所有按钮集合
            foreach (ActionCommand ac in coms)
            {
                if (ac.command == "UnReviewedData")
                {
                    ac.visible = false;
                }
                if (ac.command == "add")
                {
                    ac.visible = true;
                }
                if (ac.command == "edit")
                {
                    ac.visible = true;
                }
                if (ac.command == "SubmitData")
                {
                    ac.visible = true;
                }
                if (ac.command == "ReviewedData")
                {
                    ac.visible = false;
                }
                if (ac.command == "remove")
                {
                    ac.visible = true;
                }

            }
            return coms;
        }
    }

}
